package com.take.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.take.common.R;
import com.take.dto.DishDto;
import com.take.entity.Category;
import com.take.entity.Dish;
import com.take.entity.DishFlavor;
import com.take.service.CategoryService;
import com.take.service.DishFlavorService;
import com.take.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Api(tags = "菜品管理模块")
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "新增菜品")
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "菜品分页条件查询")
    @GetMapping("/page")
    public R<Page> page(@RequestParam(name = "page", defaultValue = "1")int page,
                        @RequestParam(name = "pageSize", defaultValue = "5")int pageSize,
                        String name,Long categoryId){

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPageInfo = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件1：菜品名称模糊查询
        queryWrapper.like(name != null,Dish::getName,name);
        //添加过滤条件2：菜品所属分类
        queryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);

        //添加排序条件
        queryWrapper.orderByDesc(Dish::getId);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝（src---->dest）
        BeanUtils.copyProperties(pageInfo,dishDtoPageInfo,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            //菜品所属分类的id
            Long dishCategoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(dishCategoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPageInfo.setRecords(list);

        return R.success(dishDtoPageInfo);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询菜品信息和对应的口味信息")
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "修改菜品")
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        return R.success("修改菜品成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        return R.success(list);
    }*/

    @ApiOperation(value = "根据条件查询菜品列表(不分页)")
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

    /*两种写法，加与不加@RequestParam注解
        1.不加@RequestParam前端的参数名需要和后端控制器的变量名保持一致才能生效。
        2.不加@RequestParam参数为非必传，加@RequestParam写法参数为必传。
        3.@RequestParam可以通过@RequestParam(required = false)设置为非必传。因为required值默认是true，所以默认必传。
        4.@RequestParam可以通过@RequestParam(“userId”)或者@RequestParam(value = “userId”)指定参数名。
    * */

    /* springmvc接收数组方式总结:
    (1)接受正常的数组
        如   param1=aaa&param1=bbb&param1=3
        对于这种，在实体参数中，使用String param1[] 这种参数既可以获取数组的值
    (2)接受数组
        比如 param1[0]=aaa,param1[1]=bbb,param1[2]=ccc
        这种，需要在实体中用List<String> param1 进行接收
    (3)接受用逗号分隔的字符串.
        这种就用字符串接收就可以了，到了后台自己进行分割处理就可以了。
    * */
    @ApiOperation(value = "批量起售、停售菜品（1=起售；0=停售）")
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") int status,@RequestParam(value="ids" ) Long[] ids){
        // @RequestParam("ids") List<Long> ids
        // @RequestParam("ids") Long[] ids
        log.info("修改菜品状态={},菜品id={}",status, ids);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        List<Dish> list = dishService.list(queryWrapper);
        list.stream().map((item) ->{
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());
        dishService.updateBatchById(list);
        return R.success("菜品售卖状态修改成功",null);
    }

    /**
     * 删除菜品（逻辑删除）
     * @param id
     * @return
     */
    @ApiOperation(value = "删除单个菜品（逻辑删除）")
    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除菜品id:{}",id);
        Assert.notNull(id, "请传入非空的菜品id");
        //删除菜品，以及相关的口味
        dishService.deleteWithFlavor(id);

        return R.success("菜品删除成功");
    }

}
